package com.efounder.frame.baseui;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.fragment.app.Fragment;
import androidx.fragment.app.FragmentManager;
import androidx.drawerlayout.widget.DrawerLayout;

import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewTreeObserver;
import android.widget.FrameLayout;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.efounder.frame.language.MultiLanguageUtil;
import com.efounder.frame.listener.EFOnTouchUDLRFlingListener;
import com.efounder.frame.manager.ScreenShotListenManager;
import com.efounder.frame.manager.ScreenShotShareManager;
import com.efounder.frame.title.EFSimpleTitleView;
import com.efounder.frame.title.EFTitleView;
import com.efounder.frame.title.EFTitleViewInterface;
import com.efounder.frame.utils.DrawerUtils;
import com.efounder.frame.xmlparse.EFRegistry;
import com.efounder.message.socket.JFAuthManager;
import com.efounder.mobilemanager.R;
import com.efounder.util.EnvSupportManager;
import com.efounder.view.CommonQMEmptyView;
import com.efounder.view.IEmptyView;
import com.efounder.view.ScreenShotDialog;
import com.gyf.immersionbar.ImmersionBar;
import com.qmuiteam.qmui.widget.QMUIEmptyView;
import com.utilcode.util.LogUtils;

import java.io.Serializable;
import java.util.List;
import java.util.Map;

import me.imid.swipebacklayout.lib.app.SwipeBackActivity;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;

public class EFActivity extends SwipeBackActivity implements EFTitleViewInterface, EasyPermissions.PermissionCallbacks {
    protected String TAG;

    /**
     * 1.DrawerLayout
     **/
    private DrawerLayout drawerLayout;
    private LinearLayout drawerLayout_contentLayout;//中间内容
    private RelativeLayout drawerLayout_leftLayout;//左侧抽屉
    private RelativeLayout drawerLayout_rightLayout;//右侧抽屉

    //右滑返回
    private boolean isCanRightSlideBack = true;//是否可以右滑返回

    protected ScreenShotListenManager screenShotListenManager;
    protected ScreenShotShareManager screenShotShareManager;
    //是否监听屏幕截图事件
    private boolean enableScreenShotListen = true;
    //是否支持监听屏幕截图事件
    private boolean isSupportListenScreenShot = false;

    //截屏后的弹窗
    private ScreenShotDialog screenShotDialog;

    /**
     * 反射主工程的分享帮助类
     */
    //private ReflectUtils reflectUtils;
    @Override
    protected void attachBaseContext(Context newBase) {
        super.attachBaseContext(MultiLanguageUtil.setLocal(newBase));
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        TAG = getClass().getSimpleName();
        super.onCreate(savedInstanceState);
        Log.i("EFActivity-----", "EFActivity-----此Activity继承自：" + EFActivity.class);
        //恢复全局的注册表数据
        if (savedInstanceState != null) {
            if (EFRegistry.getRegistryStore().size() == 0) {
                EFRegistry.setRegistryStore((Map<String, Object>) savedInstanceState.get("registryStore"));
            }
            if (EFRegistry.getAllRegistryStore().size() == 0) {
                EFRegistry.setAllRegistryStore((Map<String, Object>) savedInstanceState.get("allRegistryStore"));
            }
        }
        initScreenShotListener();

    }

    @Override
    protected void setStatusBarColor() {
        //初始化沉浸式状态栏
        if (immersionBarEnabled()) {
            //https://github.com/gyf-dev/ImmersionBar
            initImmersionBar();
        } else {
            super.setStatusBarColor();
        }
        //fixme  解决输入法遮挡问题
        try {
            //contentContainer 此id 在 efactivity中
            ViewGroup contentView = ((ViewGroup) findViewById(R.id.contentContainer));
            //contentView.setFitsSystemWindows(true);
            setApplyWindowInsets(contentView);
        } catch (Exception e) {
            Log.e("error", "设置setApplyWindowInsets失败" + getClass().getCanonicalName());
        }
    }

    @Override
    protected void onResume() {
        super.onResume();
        if (enableScreenShotListen && isSupportListenScreenShot) {
            screenShotListenManager.startListen();
        }
        if (!EnvSupportManager.isSupportIM()) {
            JFAuthManager.getInstance().requestAuth();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        screenShotListenManager.stopListen();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        screenShotShareManager.releaseUshare();

        //关闭activity前关闭弹窗
        if (screenShotDialog != null && screenShotDialog.isShowing()) {
            screenShotDialog.dismiss();
        }
    }

    private void initContentView() {
        //1.获取androidContent
        FrameLayout androidContentLayout = (FrameLayout) findViewById(android.R.id.content);
        androidContentLayout.removeAllViews();
        //2.将myLayout加入androidContent中
        getLayoutInflater().inflate(R.layout.ef_activity_frame, androidContentLayout, true);
        //3.加入titleView
        LinearLayout titleContainer = (LinearLayout) findViewById(R.id.titleContainer);
        EFSimpleTitleView titleView = new EFSimpleTitleView(this);
        titleContainer.addView(titleView);
        titleView.getLeftImageView().setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                EFActivity.this.finish();
            }
        });
        //4.初始化DrawerLayout
        initDrawerLayout();
    }

    private void initDrawerLayout() {
        drawerLayout = (DrawerLayout) findViewById(R.id.drawerLayout);
        //设置 遮罩颜色touming ，默认黑色半透明 yqs
        // drawerLayout.setScrimColor(Color.TRANSPARENT);
        // drawerLayout.setDrawerShadow(R.drawable.drawer_shadow, GravityCompat.START);
        drawerLayout_contentLayout = (LinearLayout) drawerLayout.findViewById(R.id.rootLayout);
        if (isCanRightSlideBack) {
            drawerLayout_contentLayout.requestDisallowInterceptTouchEvent(true);
//            drawerLayout_contentLayout.setOnTouchListener(new EFOnTouchBackListener(this));
            EFOnTouchUDLRFlingListener onTouchUDLRFlingListener = new EFOnTouchUDLRFlingListener(this);
            drawerLayout_contentLayout.setOnTouchListener(onTouchUDLRFlingListener);
            onTouchUDLRFlingListener.setOnFlingRightListener(new EFOnTouchUDLRFlingListener.OnFlingRightListener() {
                @Override
                public void onFlingRight(View v, MotionEvent event) {
                    EFActivity.this.finish();
                }
            });
        }
        drawerLayout_leftLayout = (RelativeLayout) drawerLayout.findViewById(R.id.left_drawer_layout);
        drawerLayout_rightLayout = (RelativeLayout) drawerLayout.findViewById(R.id.right_drawer_layout);
        //设置默认抽屉是关闭的
        drawerLayout.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {

            @SuppressWarnings("deprecation")
            @SuppressLint("NewApi")
            @Override
            public void onGlobalLayout() {

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                    drawerLayout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
                } else {
                    drawerLayout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                }
                drawerLayout.closeDrawers();
            }
        });
        drawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
        drawerLayout.addDrawerListener(new DrawerLayout.DrawerListener() {
            @Override
            public void onDrawerSlide(View drawerView, float slideOffset) {
                DrawerUtils.changeDrawerLayoutContentView(drawerLayout, drawerView, slideOffset);
            }

            @Override
            public void onDrawerOpened(View drawerView) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment leftFragment = fragmentManager.findFragmentById(R.id.left_drawer_layout);
                Fragment rightFragment = fragmentManager.findFragmentById(R.id.right_drawer_layout);
                if (leftFragment != null) {
                    leftFragment.setUserVisibleHint(true);
                }
                if (rightFragment != null) {
                    rightFragment.setUserVisibleHint(true);
                }
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                FragmentManager fragmentManager = getSupportFragmentManager();
                Fragment leftFragment = fragmentManager.findFragmentById(R.id.left_drawer_layout);
                Fragment rightFragment = fragmentManager.findFragmentById(R.id.right_drawer_layout);
                if (leftFragment != null) {
                    leftFragment.setUserVisibleHint(false);
                }
                if (rightFragment != null) {
                    rightFragment.setUserVisibleHint(false);
                }
            }

            @Override
            public void onDrawerStateChanged(int newState) {

            }
        });
    }


    @Override
    public void setContentView(int layoutResID) {
        initContentView();
        //将传入的layout加入contentContainer中
        LinearLayout contentContainer = (LinearLayout) findViewById(R.id.contentContainer);
        getLayoutInflater().inflate(layoutResID, contentContainer, true);
//        super.setContentView(myRootView);
    }

    @Override
    public void setContentView(View view) {
//        super.setContentView(view);
        initContentView();
        //将传入的layout加入contentContainer中
        LinearLayout contentContainer = (LinearLayout) findViewById(R.id.contentContainer);
        contentContainer.addView(contentContainer);
    }

    @Override
    public EFSimpleTitleView getEFTitleView() {
        LinearLayout titleContainer = (LinearLayout) findViewById(R.id.titleContainer);
        return (EFSimpleTitleView) titleContainer.getChildAt(0);
    }

    public EFTitleView replaceEFTitleView(EFTitleView titleView) {
        LinearLayout titleContainer = (LinearLayout) findViewById(R.id.titleContainer);
        titleContainer.removeAllViews();
        titleContainer.addView(titleView);
        return titleView;
    }

    public View replaceEFTitleView(View view) {
        LinearLayout titleContainer = (LinearLayout) findViewById(R.id.titleContainer);
        titleContainer.removeAllViews();
        titleContainer.addView(view);
        return view;
    }

    public void hideEFTitleView() {
        findViewById(R.id.titleContainer).setVisibility(View.GONE);
    }

    public void showEFTitleView() {
        findViewById(R.id.titleContainer).setVisibility(View.VISIBLE);
    }


    @Override
    protected void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        //存储全局的注册表数据
        outState.putSerializable("registryStore", (Serializable) EFRegistry.getRegistryStore());
        outState.putSerializable("allRegistryStore", (Serializable) EFRegistry.getAllRegistryStore());
    }

    public DrawerLayout getDrawerLayout() {
        return drawerLayout;
    }

    public LinearLayout getDrawerLayoutContentLayout() {
        return drawerLayout_contentLayout;
    }

    public int getDrawerLayoutContentLayoutResId() {
        return R.id.root_layout;
    }

    public RelativeLayout getDrawerLayoutLeftLayout() {
        return drawerLayout_leftLayout;
    }

    public int getDrawerLayoutLeftLayoutResId() {
        return R.id.left_drawer_layout;
    }

    public RelativeLayout getDrawerLayoutRightLayout() {
        return drawerLayout_rightLayout;
    }

    public int getDrawerLayoutRightLayoutResId() {
        return R.id.right_drawer_layout;
    }

    public boolean isCanRightSlideBack() {
        return isCanRightSlideBack;
    }

    public void setCanRightSlideBack(boolean canRightSlideBack) {
        isCanRightSlideBack = canRightSlideBack;
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }

    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {

    }

    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //  //如果有一些权限被永久的拒绝, 就需要转跳到 设置-->应用-->对应的App下去开启权限
        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this).setTitle(R.string.common_text_hint).setRationale(R.string.permission_remind_again).build().show();
        } else {
            somePermissionMomnetDenied(requestCode, perms);
        }
    }

    /**
     * 一些权限暂时被拒绝，子类可以重写此方法处理
     *
     * @param requestCode
     * @param perms
     */
    protected void somePermissionMomnetDenied(int requestCode, List<String> perms) {
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        screenShotShareManager.onActivityResult(requestCode, resultCode, data);
    }

    /**
     * 初始化截图监听
     */
    private void initScreenShotListener() {
        isSupportListenScreenShot = EnvSupportManager.isSupportListenScreenShot();
        screenShotListenManager = ScreenShotListenManager.newInstance(this);
        screenShotShareManager = new ScreenShotShareManager(this);
        screenShotListenManager.setListener(
                new ScreenShotListenManager.OnScreenShotListener() {
                    @Override
                    public void onShot(String imagePath) {
                        //这里我们拿到了截屏的图片
                        LogUtils.i(imagePath);
                        if (EFActivity.this != null && !EFActivity.this.isFinishing()) {
                            screenShotDialog = new ScreenShotDialog(EFActivity.this, imagePath);
                            screenShotDialog.setOnShareClickListener(new ScreenShotDialog.ShareClickListener() {
                                @Override
                                public void onShareClick(String imagePath) {
                                    gotoShare(imagePath);
                                }
                            });
                            screenShotDialog.show();
                        }
                    }
                }
        );

    }

    /**
     * 去分享
     *
     * @param imagePath
     */
    private void gotoShare(final String imagePath) {
        screenShotShareManager.shareSceenShotPic(imagePath);
    }

    /**
     * 是否允许监听屏幕截图
     *
     * @param enable
     */
    public void setEnableScreenShotListen(boolean enable) {
        enableScreenShotListen = enable;
    }


    //没有数据时显示的view
    private IEmptyView iEmptyView;
    private View contentListView;

    /**
     * 绑定空 view和显示数据的view
     *
     * @param qmuiEmptyView
     * @param view
     */
    @Deprecated
    public void bindEmptyView(QMUIEmptyView qmuiEmptyView, View view) {
        CommonQMEmptyView commonQMEmptyView = new CommonQMEmptyView();
        commonQMEmptyView.setQMUIEmptyView(qmuiEmptyView);
        this.iEmptyView = commonQMEmptyView;
        this.contentListView = view;
    }

    public void bindEmptyView(IEmptyView iEmptyView, View view) {
        this.iEmptyView = iEmptyView;
        this.contentListView = view;
    }

    /**
     * 用于显示纯文本的简单调用方法，此时loading、button均被隐藏
     *
     * @param titleText  标题的文字，不需要则传null
     * @param detailText 详情文字，不需要则传null
     */
    public void showEmptyView(String titleText, String detailText) {
        iEmptyView.show(titleText, detailText);

        contentListView.setVisibility(View.GONE);

    }

    /**
     * 用于显示纯文本的简单调用方法，此时loading、button均被隐藏
     *
     * @param titleText 标题的文字，不需要则传null
     */
    public void showEmptyView(String titleText, String buttonText, View.OnClickListener onClickListener) {
        iEmptyView.show(false, titleText, null, buttonText, onClickListener);
        contentListView.setVisibility(View.GONE);
    }

    /**
     * 显示网络异常
     */
    public void showNetError() {
        iEmptyView.showNetError();
        contentListView.setVisibility(View.GONE);
    }

    /**
     * 显示暂无数据
     */
    public void showNoDatas() {
        iEmptyView.showNoData();
        contentListView.setVisibility(View.GONE);
    }

    public void hideEmptyView() {
        iEmptyView.hide();
        contentListView.setVisibility(View.VISIBLE);
    }

    public void initImmersionBar() {
        ImmersionBar.with(this).init();
    }

    /**
     * 是否可以实现沉浸式，当为true的时候才可以执行initImmersionBar方法
     * Immersion bar enabled boolean.
     *
     * @return the boolean
     */
    public boolean immersionBarEnabled() {
        return EnvSupportManager.isUseTransparentStatus();
    }
}
